package com.neuedu.it.teach.controller;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.neuedu.it.teach.controller.vo.Result;
import com.neuedu.it.teach.service.HelpService;
import io.reactivex.Flowable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;  // 添加这行导入
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
public class PostAIController {
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    @PostMapping(value = "/api/deepseek/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamDeepSeek(@RequestBody Map<String, Object> requestBody) {
        SseEmitter emitter = new SseEmitter(-1L); // 无超时
        
        executorService.execute(() -> {
            try {
                // 从请求体中获取问题
                String question = (String) requestBody.get("question");
                String localhost = (String) requestBody.get("localhost");
                System.out.println("获取到的localhost: " + localhost);
                String dataInfo = getHelpInfo(localhost);
                System.out.println("获取到的互助信息: " + getHelpInfo(localhost));
                if (question == null || question.trim().isEmpty()) {
                    sendError(emitter, "问题不能为空");
                    return;
                }
                
                // 创建生成参数
                Generation gen = new Generation();
                GenerationParam generationParam = buildDeepSeekGenerationParam(question,dataInfo);
                Flowable<GenerationResult> result = gen.streamCall(generationParam);
                
                // 处理流式响应
                result.blockingForEach(message -> {
                    try {
                        handleStreamingResult(emitter, message);
                    } catch (IOException e) {
                        throw new RuntimeException("发送SSE事件失败", e);
                    }
                });
                
                // 发送完成标记
                emitter.send(SseEmitter.event().name("message").data("[DONE]", MediaType.TEXT_PLAIN));
                emitter.complete();
            } catch (Exception e) {
                try {
                    sendError(emitter, "处理请求时发生错误: " + e.getMessage());
                } catch (IOException ex) {
                    emitter.completeWithError(ex);
                }
            }
        });
        
        return emitter;
    }
    
    private void handleStreamingResult(SseEmitter emitter, GenerationResult message) throws IOException {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
        // 获取互助信息并格式化
        // getHelpInfo();
        // 构建与前端期望格式匹配的JSON响应
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{\"choices\":[{\"delta\":{");
        
        boolean hasContent = false;
        
        // 添加思考过程（如果有）
        if (reasoning != null && !reasoning.isEmpty()) {
            jsonBuilder.append("\"reasoning_content\":\"")
                    .append(escapeJsonString(reasoning))
                    .append("\"");
            hasContent = true;
        }
        
        // 添加内容（如果有）
        if (content != null && !content.isEmpty()) {
            if (hasContent) {
                jsonBuilder.append(",");
            }
            jsonBuilder.append("\"content\":\"")
                    .append(escapeJsonString(content))
                    .append("\"");
        }
        
        jsonBuilder.append("}}]}");
        
        // 发送SSE事件
        emitter.send(SseEmitter.event()
                .name("message")
                .data(jsonBuilder.toString(), MediaType.TEXT_PLAIN));
    }
    
    private void sendError(SseEmitter emitter, String errorMessage) throws IOException {
        String errorJson = "{\"error\":\"" + escapeJsonString(errorMessage) + "\"}"; 
        emitter.send(SseEmitter.event()
                .name("message")
                .data(errorJson, MediaType.TEXT_PLAIN));
        emitter.complete();
    }
    
    private static GenerationParam buildDeepSeekGenerationParam(String msg,String dataInfo) {
        List<Message> messages = new ArrayList<>();
        String systemInfo = "你是一个名为知乡的乡村儿童助教平台的助手，提供给你要查找的学生情况和数据库中的求助数据，" +
                "根据学生情况从数据库数据中选出符合条件的学生推荐给用户，可以多个，说明理由，" +
                "最终以markdown的形式将url渲染出来给用户，例如[查看详情](http://localhost:5173/home/detail/7)，请以合理美观的markdown格式回答用户问题，";

        // 添加助手消息
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content(systemInfo)
                .build();

        // 添加助手消息
        Message assistantMsg = Message.builder()
                .role(Role.ASSISTANT.getValue())
                .content(dataInfo)
                .build();

        // 添加用户消息
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(msg)
                .build();

        messages.add(systemMsg);
        messages.add(assistantMsg);
        messages.add(userMsg);

        // Message userMsg = Message.builder().role(Role.USER.getValue()).content(msg).build();
        return GenerationParam.builder()
                .apiKey("sk-893ad79db95a4414ade4fd5f6e6605fa")
                .model("deepseek-v3")
                .messages(messages) // 使用构建的消息列表
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }
    
    // 辅助方法：转义JSON字符串
    private String escapeJsonString(String input) {
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    @Autowired
    private HelpService helpService;
    
    private String getHelpInfo(String localhost){
        try {
            List<Map<String, Object>> pendingHelps = helpService.getAllPendingHelp();
            System.out.println("获取到的待处理互助信息: " + (pendingHelps != null ? pendingHelps.toString() : "null"));
            if(pendingHelps != null) {
                // 使用HelpDataFormatter格式化互助信息并构建对话内容
                return com.neuedu.it.teach.utils.HelpDataFormatter.buildDialogueContent(pendingHelps, localhost);
            }
        } catch (Exception e) {
            System.err.println("获取互助信息失败: " + e.getMessage());
        }
        return null;
    }
}